<?php

require('wephp/web.php');

$urls = array(
	'/' => 'index',
    '/edit/*' => 'edit',
    '/delete/*' => 'delete',
    '/add' => 'add',
);

$db_parameters = array(
    'user'=> 'root',
    'pw' => '',
    'db' => 'wephp_blog'
);

function base_url() {
    $base = '/news/wephp';
    return $base;
}

class index {
    function GET($path,$db) {
        $query = $db->query('SELECT * FROM posts');
        $ins['posts'] = $query->fetchall();
        echo web::render('index.php', $ins);
    }
}

class edit {
	function GET($path, $db) {
        $seg = $path->pathVars[1];
        $query = $db->query('SELECT * FROM posts WHERE id = '.$seg);
        //only need to fetch 1 here
        $ins['post'] = $query->fetch();
        echo web::render('edit.php', $ins);
    }
    
    function POST($path, $db) {
        $db->query("UPDATE posts SET title = '".$_POST['title']."', date = '".$_POST['date']."', text = '".$_POST['text']."' WHERE id = ".$_POST['id']);
        web::redirect(base_url());
    }

}

class delete {
    function GET($path, $db) {
        $seg = $path->pathVars[1];
        $db->query("DELETE FROM posts WHERE id = ".$seg);
        web::redirect(base_url());
    }
}

class add {
    function GET($path) {
        echo web::render('add.php');
    }
    
    function POST($path, $db) {
        $db->query("INSERT INTO posts (title, date, text) VALUES ('".$_POST['title']."', '".$_POST['date']."', '".$_POST['text']."')");
        web::redirect(base_url());
    }
}

web::run($urls, $db_parameters);

?>
